#!/bin/bash
#########################################################################
#
# File:         kiserver.sh
# Description:  Gen graph and dashboard for kibana from  Nagios configure.
# Language:     GNU Bourne-Again SHell
# Version:      1.1.1
# Date:         2016-12-14
# Corp.:        liaoyichang
# Author:       atdmliaod@tom.com
#########################################################################
SOURCE="$( cd "$( dirname "$0"  )" && pwd  )"
NAGIOS_DIR=@nagios_dir@
NAGIOS_ED=@tools@/cfr
NG_DIR=@ng_dir@

NAGIOS_CFG=$NAGIOS_DIR/etc

group_mode=0
Hosts=""

print_help_msg(){
        print_version
        $ECHO "Usage: $0 -h to get help."
        $ECHO
        $ECHO 'Report bugs to: liaoyq@tom.com'
}
print_full_help_msg(){
        print_version
        $ECHO "Usage:"
        $ECHO "$0 [ -v ] [-g group|-s hosts]"
}
print_version(){
        $ECHO $(cat $0 | head -n 7 | tail -n 1|sed 's/\# //')
}
to_debug(){
$ECHO "$*"
if [ "$Debug" = "true" ]; then
        $ECHO "$*" >> /tmp/run.log 2>&1
fi
}


case "$(uname -s)"
        in
        SunOS)
        ECHO="echo"
        ;;
        Linux)
        ECHO="echo -e"
        ;;
        *)
        ECHO="echo"
        ;;
esac

        while getopts :vzhs:g: OPTION
        do
                case $OPTION
                        in
                        v)
                        $ECHO "Verbose mode."
                        Debug=true
                        ;;
                        z)
                        zDebug=true
                        ;;
                        s)
                        Hosts=$OPTARG
                        ;;
                        h)
                        print_full_help_msg
                        exit 3
                        ;;
                        g)
                         group_mode=1
                         Hosts=$OPTARG
                        ;;
                        ?)
                        $ECHO "Error: Illegal Option."
                        print_help_msg
                        exit 3
                        ;;
                esac
        done


if [ "$Hosts""ZZZ" == "ZZZ" ]; then
    $ECHO "You MUST use parameter -g or -s"
    exit 3
fi


AWK=`which awk 2>&1`
if [ $? -ne 0 ];then
        $ECHO $AWK
        $ECHO "Can not found command awk in you system PATH: $PATH, pleas check it"
        exit 3
fi
to_debug Use $AWK to calculate

if [ "$group_mode" == "1" ]; then
   files=`cat $NAGIOS_DIR/all|grep $Hosts|awk '{print $1}'`
else
   files="$Hosts"
fi
for i in $files; do
     $ECHO "Host $i"
     n1=`$ECHO "$i"|awk -F. '{printf "%d.%d" , $3 , $4}'`
     tmp=`$NAGIOS_ED -l -g service $NAGIOS_CFG/servers/$i.cfg service_description |awk '{ print $2}'`
     for k in $tmp; do
        $NG_DIR/ngraph -s $k -n $n1
     done
     sleep 3
     $NG_DIR/ndash -n $n1
done
